package com.lujieni.springbootjvm.classloader;

import com.lujieni.springbootjvm.po.CardInfo;

import java.io.*;


/**
 *  1.重写java中类加载器的顶级抽象类ClassLoader中的findClass方法即可；
 *  2.不重写loadClass方法是为了不破坏类加载器的双亲委派机制
 *  3.对字节码文件的加解密操作可以根据实际情况自定义
 *
 * @param className
 * @return
 * @throws ClassNotFoundException
 */
public class MyClassLoader extends ClassLoader{


    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> cardInfo = myClassLoader.findClass("com.lujieni.springbootjvm.po.CardInfo");
        System.out.println(cardInfo.getName());
        System.out.println(cardInfo.getClassLoader());
        System.out.println(cardInfo.getClassLoader().getParent());

    }

    protected Class<?> findClass(String className) throws ClassNotFoundException {
        String path = "D:/IDEA_WORKSPACE/springboot-jvm/target/classes/";
        String fileName = path + className.replaceAll("\\.", "/") + ".class";

        System.out.println(fileName);

        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            //将文件通过流读入内存数组中
            fis= new FileInputStream(fileName);

            bos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int n = 0;
            while ((n = fis.read(buffer)) != -1) {
                bos.write(buffer,0, n);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                bos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return defineClass(className, bos.toByteArray(), 0,  bos.toByteArray().length);
    }


}
